﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;

using Microsoft.ApplicationBlocks.Data;

namespace DbAccessTester
{
   public class ConnectionModel
   {
      public string Server { get; set; }
      public string Database { get; set; }
      public string UID { get; set; }
      public string PWD { get; set; }
      public string Sql { get; set; }
      public string ErrorText { get; set; }
      public string ConnectionString { get; set; }
      public bool HasError { get; set; }
      public bool HasFullConnectionString { get; set; }

      public string GetConnectionString()
      {
         if (this.HasFullConnectionString) return this.ConnectionString;

         string beginConnectionString = ConfigurationManager.AppSettings["beginConnectionString"];
         if (string.IsNullOrEmpty(beginConnectionString))
            beginConnectionString = "Persist Security Info=False;Application Name=BinojCnnTester1;Connect Timeout=10;";

         bool isSSPI = (string.IsNullOrEmpty(this.UID) || string.IsNullOrEmpty(this.PWD));
         this.ConnectionString = beginConnectionString + "server=" + this.Server + ";database=" + this.Database + ";";
         if (isSSPI)
            this.ConnectionString = this.ConnectionString + "Integrated Security=SSPI;";
         else
            this.ConnectionString = this.ConnectionString + "User ID=" + this.UID + ";Password=" + this.PWD + ";";

         return this.ConnectionString;
      }

      public DataSet ExecuteDataSet()
      { 
         string connectionString = this.GetConnectionString();
         DataSet dataSet = null;
         try
         {
            dataSet = SqlHelper.ExecuteDataset(connectionString, CommandType.Text, this.Sql);
            this.HasError = false;
         }
         catch (Exception ex)
         {
            this.HasError = true;
            this.ErrorText = ex.ToString();
         }
         return dataSet;
      }

      public bool CheckConnection()
      {
         string connectionString = this.GetConnectionString();
         SqlConnection conn = null;
         try
         {
            conn = new SqlConnection(connectionString);
            conn.Open();
            this.HasError = false;
         }
         catch (Exception ex)
         {
            this.HasError = true;
            this.ErrorText = ex.ToString();
            return false;
         }
         finally
         {
            if (conn != null) conn.Dispose();
         }
         return true;
      }
   }
}
//Copyright Binoj V Antony © 2011 under GNU Library General Public License (LGPL) at http://DbAccessTesterClient.CodePlex.com/
//Please preserve the authors names and copyright statement in the code even when the work is changed or added to.